package com.yanyu.space.common.cloud.feign;

import com.yanyu.space.common.core.bean.web.R;
import com.yanyu.space.common.core.bean.web.RCode;
import com.yanyu.space.common.core.util.WebUtil;
import feign.RetryableException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.net.UnknownHostException;


/**
 * 全局异常
 * @author yanyu
 */
@Slf4j
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE - 5)
public class FeignGlobalExceptionHandler {

    /**
     * 当开启fegin重试，并且没有获取对应的服务会抛出异常，如果配置sentinel断路器，将不走此处
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = RetryableException.class)
    public R handlerRetryableException(RetryableException e) {
        log.error("error by handlerRetryableException , url {}", WebUtil.getUrl(), e);
        if (e.getCause() instanceof UnknownHostException) {
            return R.fail(RCode.SERVICE_UNAVAILABLE);
        }
        return R.fail();
    }
}
